import * as echarts from 'echarts/core'
import { merge } from 'lodash'
import computedIntervalData from './computed-interval'

const fontSize = 14
// 文字颜色
const textColor = '#333'
const splitLineColor = '#EEEEEE'
const axisColor = '#999999'

function mergeLegend(legend = {}) {
  const initLegend = {
    textStyle: {
      color: textColor,
      fontSize
    }
  }
  return merge({}, initLegend, legend)
}

function mergeToolTip(tooltip = {}) {
  const initTooltip = {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    confine: true,
    textStyle: {
      fontSize
    }
  }
  return merge({}, initTooltip, tooltip)
}

function mergeGrid(grid: any) {
  const initGrid = {
    containLabel: true
  }
  return merge({}, initGrid, grid)
}

function mergeXAxis(xAxis: any) {
  const initXAxis = {
    type: 'category',
    axisLabel: {
      color: axisColor,
      fontSize
    },
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    splitLine: {
      show: false
    }
  }

  let updateXAxis
  if (Array.isArray(xAxis)) {
    ;[updateXAxis] = xAxis
  } else {
    updateXAxis = xAxis
  }
  return [merge({}, initXAxis, updateXAxis)]
}

function mergeYAxis(series: any[] = [], yAxis: any) {
  let min
  let max
  let interval
  let updateYAxis
  if (Array.isArray(yAxis)) {
    ;[updateYAxis] = yAxis
  } else {
    updateYAxis = yAxis || {}
  }
  if (series.length && updateYAxis.type !== 'category') {
    const data: any[] = []
    series.forEach((first: any) => {
      first.data.forEach((item: any) => {
        data.push(item)
      })
    })
    const intervalObj: any = computedIntervalData({ data })
    min = intervalObj.min
    max = intervalObj.max
    interval = intervalObj.interval
  }
  const initYAxis = [
    {
      type: 'value',
      scale: true,
      min,
      max,
      interval,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed', // 设置分隔线为虚线
          color: '#eee', // 设置分隔线颜色
          width: 1 // 设置分隔线宽度
        }
      },
      axisLabel: {
        color: axisColor,
        fontSize
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      }
    }
  ]
  if (updateYAxis && updateYAxis.valueData) {
    const intervalObj = computedIntervalData({ data: updateYAxis.valueData })
    initYAxis[0].min = intervalObj.min
    initYAxis[0].max = intervalObj.max
    initYAxis[0].interval = intervalObj.interval
  }
  return [merge({}, initYAxis[0], updateYAxis)]
}

function mergeSeries(series: any[] = []) {
  const initSeries = {
    type: 'bar',
    barWidth: '12',
    showBackground: false,
    backgroundStyle: {
      color: '#EDF7FF'
    },
    color: {}
  }
  let lastSeries: any[] = []
  const defaultLinearColor = ['#64AFFF', '#1492FF']
  series.forEach((item: any) => {
    let color1
    let color2
    if (item.colorList) {
      ;[color1, color2] = item.colorList
    }
    initSeries.color = {
      x: 0,
      y: 1,
      x2: 0,
      y2: 0,
      type: 'linear',
      global: false,
      colorStops: [
        {
          offset: 0,
          color: color1 || defaultLinearColor[0]
        },
        {
          offset: 1,
          color: color2 || defaultLinearColor[1]
        }
      ]
    }
    lastSeries.push(merge({}, initSeries, item))
  })
  if (!lastSeries.length) {
    lastSeries = [initSeries]
  }
  return lastSeries
}

interface chartProps {
  dom: string
  title?: object
  tooltip?: object
  legend?: object
  grid?: object
  xAxis?: object | object[]
  yAxis?: object | object[]
  series: any[]
  data?: any[]
  color?: string[] | undefined
  highlightEvent?: (params: any) => void
  speed?: number
  clickEvent?: (params: any) => void
  extendSign?: boolean
}
// 圆角柱状图
export class HsGlobalCircleBarChart {
  public myChart: any
  public option: any
  public clickEvent: (params: any) => void
  constructor({ dom, tooltip, legend, grid, xAxis, yAxis, series, color, clickEvent, extendSign, ...rest }: chartProps) {
    // 销毁重新绘制
    if (document.getElementById(dom)) {
      document.getElementById(dom)?.removeAttribute('_echarts_instance_')
    }
    const _legend = mergeLegend(legend)
    const _tooltip = mergeToolTip(tooltip)
    const _grid = mergeGrid(grid)
    const _xAxis = mergeXAxis(xAxis)
    const _yAxis = mergeYAxis(series || [], yAxis)
    const _series = mergeSeries(series)
    this.option = {}
    this.clickEvent =
      clickEvent ||
      (() => {
        //
      })
    if (!extendSign) {
      this.init(dom, color, _legend, _tooltip, _grid, _xAxis, _yAxis, _series, rest)
    }
  }

  init(
    dom: string,
    color: string[] | undefined,
    legend: object,
    tooltip: object,
    grid: object,
    xAxis: object | object[],
    yAxis: object | object[],
    series: any[],
    rest: any
  ) {
    // 基于准备好的dom，初始化echarts实例
    this.myChart = echarts.init(document.getElementById(dom) as HTMLElement)
    // 绘制图表
    this.option = {
      color: color || [
        '#46A0FF',
        '#FFC64C',
        '#63E587',
        '#FA885D',
        '#7BF0EB',
        '#F277E1',
        '#FF7B7B',
        '#728EFE',
        '#E1EC9E',
        '#8F2EFF',
        '#8DEEFF',
        '#7C69F2',
        '#CCF6B5',
        '#EE8989',
        '#84B2FF',
        '#80E5C4'
      ],
      legend,
      tooltip,
      grid,
      xAxis,
      yAxis,
      series,
      ...rest
    }
    this.myChart.setOption(this.option)
    window.addEventListener('resize', () => this.myChart.resize(), false)
    this.myChart.on('click', (params: any) => {
      this.clickEvent(params)
    })
  }
}

export class HsGlobalBarLineChart extends HsGlobalCircleBarChart {
  constructor(props: chartProps) {
    const { dom, tooltip, legend, grid, xAxis, yAxis, series, color, ...rest } = props
    props.extendSign = true
    super(props)
    const _legend = this.mergeLegend(legend)
    const _tooltip = mergeToolTip(tooltip)
    const _grid = mergeGrid(grid)
    const _xAxis = mergeXAxis(xAxis)
    const _yAxis = this.mergeYAxis(yAxis)
    const _series = this.mergeSeries(series)
    this.init(dom, color, _legend, _tooltip, _grid, _xAxis, _yAxis, _series, rest)
  }

  mergeSeries(series: any[] = []) {
    const handleBarSeries = (seriesParams: { colorList: [any, any] }) => {
      const initBarSeries = {
        type: 'bar',
        barWidth: '16',
        itemStyle: {
          borderRadius: [16, 16, 0, 0]
        },
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(51,147,198,0)',
          borderWidth: 1,
          borderColor: 'rgba(51,147,198,0.2)',
          borderRadius: [16, 16, 0, 0]
        },
        color: {}
      }
      let color1
      let color2
      if (seriesParams.colorList) {
        ;[color1, color2] = seriesParams.colorList
      }
      initBarSeries.color = {
        x: 0,
        y: 1,
        x2: 0,
        y2: 0,
        type: 'linear',
        global: false,
        colorStops: [
          {
            offset: 0,
            color: color1 || '#265CD4'
          },
          {
            offset: 1,
            color: color2 || '#33ADF1'
          }
        ]
      }
      return merge({}, initBarSeries, seriesParams)
    }
    const handleLineSeries = (seriesParams: any) => {
      const initLineSeries = {
        type: 'line',
        color: 'rgba(229,182,52,1)'
      }
      return merge({}, initLineSeries, seriesParams)
    }

    const lastSeries: any[] = []
    series.forEach((item, index) => {
      let yAxisIndex = 0
      if (index) {
        yAxisIndex = 1
      }
      if (item.type === 'bar') {
        lastSeries.push(handleBarSeries({ yAxisIndex, ...item }))
      } else if (item.type === 'line') {
        lastSeries.push(handleLineSeries({ yAxisIndex, ...item }))
      }
    })
    return lastSeries
  }

  mergeYAxis(yAxis: object | object[] = []) {
    const initYAxis: any[] = [
      {
        type: 'value',
        scale: true,
        splitLine: {
          show: true,
          lineStyle: {
            color: splitLineColor,
            type: 'dashed'
          }
        },
        axisLabel: {
          color: axisColor,
          fontSize
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        }
      },
      {
        type: 'value',
        scale: true,
        splitLine: {
          show: false
        },
        axisLabel: {
          color: axisColor,
          fontSize
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        }
      }
    ]
    const lastYAxis = []
    if (Array.isArray(yAxis) && yAxis.length) {
      if (yAxis[0].valueData) {
        const intervalObj = computedIntervalData({ data: yAxis[0].valueData })
        initYAxis[0].min = intervalObj.min
        initYAxis[0].max = intervalObj.max
        initYAxis[0].interval = intervalObj.interval
      }
      lastYAxis.push(merge({}, initYAxis[0], yAxis[0]))
      if (yAxis[1]) {
        const intervalObj = computedIntervalData({ data: yAxis[1].valueData })
        initYAxis[1].min = intervalObj.min
        initYAxis[1].max = intervalObj.max
        initYAxis[1].interval = intervalObj.interval
        lastYAxis.push(merge({}, initYAxis[1], yAxis[1]))
      }
    }
    return lastYAxis
  }

  mergeLegend(legend = {}) {
    const initLegend = {
      textStyle: {
        color: textColor,
        fontSize
      },
      itemWidth: 6,
      icon: 'rect'
    }
    return merge({}, initLegend, legend)
  }
}
